package com.promfy.anonymousshare;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CalendarContract.Reminders;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.promfy.anonymousshare.domain.Action;
import com.promfy.anonymousshare.views.PopMenu;
import com.promfy.anonymousshare.views.PullDownView;
import com.promfy.anonymousshare.views.PullDownView.OnPullDownListener;

public class HomeActivity extends Activity implements OnClickListener,OnPullDownListener, OnItemClickListener{
	/**
	 * for pop menu
	 */
	private PopMenu classifyPopMenu;
	private Button titleBtn;
	private ImageButton addIBtn;
	
	/**
	 * for pull down listview
	 */
	private static final int WHAT_DID_LOAD_DATA = 0;
	private static final int WHAT_DID_REFRESH = 1;
	private static final int WHAT_DID_MORE = 2;
	private PullDownView mPullDownView;
	private ListView mListView;
	private ArrayAdapter<String> mAdapter;
	private List<Action> actions = new ArrayList<Action>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.tab_main);

		initView();
		
		loadData();
	}

	private void initView() {
		titleBtn = (Button)findViewById(R.id.title_btn);
		addIBtn = (ImageButton)findViewById(R.id.add_image_btn);
		titleBtn.setOnClickListener(this);
		addIBtn.setOnClickListener(this);
		
		//popmenu
		classifyPopMenu = new PopMenu(this);
		classifyPopMenu.addItems(new String[] { "send", "receive", "..."});
		classifyPopMenu.setOnItemClickListener(popmenuItemClickListener);
		
		//pullDownView
		mPullDownView = (PullDownView) findViewById(R.id.pull_down_view);
		mPullDownView.setOnPullDownListener(this);
		mListView = mPullDownView.getListView();
		
		mListView.setOnItemClickListener(this);
//		mAdapter = new ArrayAdapter<String>(this, R.layout.msg_item, mStrings);
		mAdapter = new MsgListAdapter(this, 0, R.layout.msg_item, actions);
		
        mListView.setAdapter(mAdapter);
        
        mPullDownView.enableAutoFetchMore(true, 1);
	}

    
	OnItemClickListener popmenuItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
			classifyPopMenu.dismiss();
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_btn:
			classifyPopMenu.showAsDropDown(v);
			break;
        case R.id.add_image_btn:
        	//jump to ActionEditActivity
			break;
		default:
			break;
		}
	}

	private void loadData(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				List<Action> ats = new ArrayList<Action>();
				for (String body : mStringArray) {
					Action at = new Action(Action.Cata.SEND, System.currentTimeMillis(), body);
					ats.add(at);
				}
				Message msg = mUIHandler.obtainMessage(WHAT_DID_LOAD_DATA);
				msg.obj = ats;
				msg.sendToTarget();
			}
		}).start();
	}


	@Override
	public void onRefresh() {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}				
				Message msg = mUIHandler.obtainMessage(WHAT_DID_REFRESH);
				msg.obj = new Action(Action.Cata.RECEIVED, System.currentTimeMillis(), "onRefresh " + System.currentTimeMillis());
				msg.sendToTarget();
			}
		}).start();
	}
	
	@Override
	public void onMore() {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}				
				Message msg = mUIHandler.obtainMessage(WHAT_DID_MORE);
				msg.obj = new Action(Action.Cata.RECEIVED, System.currentTimeMillis(), "onMore " + System.currentTimeMillis());
				msg.sendToTarget();
			}
		}).start();
	}
	
	private Handler mUIHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case WHAT_DID_LOAD_DATA:{
					if(msg.obj != null){
						List<Action> ats = (List<Action>) msg.obj;
						if(!ats.isEmpty()){
							actions.addAll(ats);
							mAdapter.notifyDataSetChanged();
						}
					}
					// 诉它数据加载完毕;
					mPullDownView.notifyDidLoad();
					break;
				}
				case WHAT_DID_REFRESH :{
					Action body = (Action) msg.obj;
					actions.add(0, body);
					mAdapter.notifyDataSetChanged();
					// 告诉它更新完毕
					mPullDownView.notifyDidRefresh();
					break;
				}
				
				case WHAT_DID_MORE:{
					Action body = (Action) msg.obj;
					actions.add(body);
					mAdapter.notifyDataSetChanged();
					// 告诉它获取更多完毕
					mPullDownView.notifyDidMore();
					break;
				}
			}
			
		}
		
	};

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Toast.makeText(this, "啊，你点中我了 " + position, Toast.LENGTH_SHORT).show();
	}
	
	
	
	// 模拟数据
	private String[] mStringArray = {
            "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
            "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
            "Aisy Cendre", "Allgauer Emmentaler", "Alverca", "Ambert", "American Cheese"
    };

	
	private class MsgListAdapter extends ArrayAdapter {

		private LayoutInflater inflater;
		private ArrayList<Action> actionList;


		public MsgListAdapter(Context context, int resource, int textViewResourceId, List objects) {
			super(context, resource, textViewResourceId, objects);
			inflater = LayoutInflater.from(context);
			actionList = (ArrayList<Action>) objects;

		}

		@Override
		public Object getItem(int position) {
			return actionList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.msg_item, null);

				holder = new ViewHolder();
				holder.cata = (ImageView) convertView.findViewById(R.id.msg_cata_iv);
				holder.date = (TextView) convertView.findViewById(R.id.date_tv);
				holder.content = (TextView) convertView.findViewById(R.id.content_tv);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			try {

				Action at = (Action) getItem(position);
				holder.date.setText(at.getDate()+"");
				holder.content.setText(at.getContent());
				if(at.getCata() == Action.Cata.RECEIVED){
					holder.cata.setImageResource(R.drawable.icon_1_n);
				}else{
					holder.cata.setImageResource(R.drawable.icon_2_n);					
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}

			return convertView;
		}

		class ViewHolder {
			ImageView cata;
			TextView date;
			TextView content;
		}

		@Override
		public int getCount() {
			return actionList.size();
		}

	}
}
